package com.itheima01;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class MyDataSource implements DataSource {
    private static List<Connection> conns = new ArrayList<>();


    public MyDataSource() throws SQLException {
        for (int i = 0; i < 3; i++) {
            conns.add(JdbcUtils.getCon());
        }
    }


    @Override
    public Connection getConnection() throws SQLException {
        System.out.println(conns);
        Connection conn = conns.remove(0);
        System.out.println(conn);

//        return new MyConnection1(conn,conns);
        //使用动态代理方式
        return (Connection) Proxy.newProxyInstance(MyDataSource.class.getClassLoader(), new Class[]{Connection.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //对close方法进行增强
                if ("close".equals(method.getName())){
                    conns.add(conn);
                    return null;
                }

                return method.invoke(conn,args);
            }
        });

    }




    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
